package com.hackdf.ecographic;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import android.util.Log;

public class Parser {
	private String reporte = "reporte";

	/** CALIDAD **/
	private String categoria = "categoria";
	private String color = "color";
	private String recomendaciones = "recomendaciones";

	/** CLIMA **/
	private String temperatura = "temperatura";
	private String condicion = "condicion";

	/** UV **/
	private String indice = "indice";
	private String color_uv = "color";
	private String recomendaciones_uv = "recomendaciones";

	private String urlString = null;

	public Parser(String url){
		this.urlString = url;
	}

	public String getCategoria(){
		return categoria;
	}

	public String getColor(){
		return color;
	}

	public String getRecomendaciones(){
		return recomendaciones;
	}
	public String getTemperatura(){
		return temperatura;
	}

	public String getCondicion(){
		return condicion;
	}

	public String getIndice(){
		return indice;
	}

	public String getColoUV(){
		return color_uv;
	}

	public String getRecomendaciones_uv(){
		return recomendaciones_uv;
	}

	public void readAndParseJSON(String in){

		try {
			JSONObject reader = new JSONObject(in);

			JSONObject consulta = reader.getJSONObject("consulta");

			JSONObject calidad = consulta.getJSONObject("calidad");
			categoria = calidad.getString("categoria");
			color = calidad.getString("color");
			recomendaciones = calidad.getString("recomendaciones");

			JSONObject clima = consulta.getJSONObject("clima");
			temperatura = clima.getString("temperatura");
			condicion = clima.getString("condicion");

			JSONObject uv = consulta.getJSONObject("uv");
			indice = uv.getString("indice");
			color_uv = uv.getString("color");
			recomendaciones_uv = uv.getString("recomendaciones");

			Log.i("datos importantes", getCategoria() +  " " + getColor() + "  " + getRecomendaciones() + " " + getTemperatura() + " " + getCondicion()
					+ " " + getIndice() + " " + getColoUV() + " " + getRecomendaciones_uv());

		} catch (Exception e) {
		}

	}
	public void fetchJSON(){
		try {
			URL url = new URL(urlString);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(10000 /* milliseconds */);
			conn.setConnectTimeout(15000 /* milliseconds */);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			// Starts the query
			conn.connect();
			InputStream stream = conn.getInputStream();

			String data = convertStreamToString(stream);
			Log.i("data", data);
			readAndParseJSON(data);
			stream.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	static String convertStreamToString(java.io.InputStream is) {
		java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
		return s.hasNext() ? s.next() : "";
	}
}
